import { ref, inject, provide } from 'vue';
import { COZE_CN_BASE_URL, RoleType } from '@coze/api';
import { CozeAPI } from '@coze/uniapp-api';

// 创建注入键
const cozeKey = Symbol('coze');

export function createCozeClient(config) {
  const client = new CozeAPI({
    baseURL: COZE_CN_BASE_URL,
    ...config
  });
  provide(cozeKey, client);
  return client;
}

export function useCoze() {
  const client = inject(cozeKey);
  if (!client) {
    throw new Error('请先调用createCozeClient初始化');
  }
  return client;
}

// 对话管理组合式函数
export function useChat(botId) {
  const messages = ref([]);
  const isLoading = ref(false);
  const error = ref(null);
  const client = useCoze();

  // 发送消息
  const sendMessage = async (content) => {
    isLoading.value = true;
    error.value = null;
    
    const userMsg = {
      role: RoleType.User,
      content,
      content_type: 'text'
    };
    
    messages.value.push({
      ...userMsg,
      timestamp: new Date().toISOString()
    });

    try {
      const response = await client.chat.createAndPoll({
        bot_id: botId,
        additional_messages: [userMsg]
      });

      if (response.chat.status === 'completed') {
        response.messages.forEach(msg => {
          messages.value.push({
            ...msg,
            timestamp: new Date().toISOString()
          });
        });
      }
      return response;
    } catch (err) {
      error.value = err.message || '发送失败，请重试';
      console.error('对话错误:', err);
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  // 流式发送
  const streamMessage = async (content) => {
    isLoading.value = true;
    error.value = null;
    
    const userMsg = {
      role: RoleType.User,
      content,
      content_type: 'text',
      timestamp: new Date().toISOString()
    };
    
    messages.value.push(userMsg);
    
    // 创建助手消息占位符
    const assistantMsg = {
      role: 'assistant',
      content: '',
      timestamp: new Date().toISOString()
    };
    messages.value.push(assistantMsg);

    try {
      const stream = await client.chat.stream({
        bot_id: botId,
        additional_messages: [userMsg]
      });

      for await (const part of stream) {
        if (part.event === 'conversation.message.delta' && part.data?.content) {
		  messages.value[messages.value.length - 1].content += part.data.content;
		  
        }
      }
      return assistantMsg.content;
    } catch (err) {
      error.value = err.message || '流式请求失败';
      console.error('流式错误:', err);
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  // 清空对话
  const clearMessages = () => {
    messages.value = [];
  };

  return {
    messages,
    isLoading,
    error,
    sendMessage,
    streamMessage,
    clearMessages
  };
}